package com.kgcx.common.handler;

import com.kgcx.common.bean.ReturnData;
import com.kgcx.common.utils.CollectionUtils;
import com.kgcx.common.utils.SensitiveUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.lang.Nullable;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 拦截所有返回的json对象，如发现Sensitive敏感字段，根据配置解密以及隐藏
 *
 * @author 吴刚林
 * @date 2017/11/26
 */
@ControllerAdvice
@Slf4j
public class SensitiveHideResponseBodyAdviceAdapter implements ResponseBodyAdvice {
    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Nullable
    @Override
    public Object beforeBodyWrite(@Nullable Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (null != body && body instanceof ReturnData) {
            ReturnData returnData = (ReturnData) body;
            if (null != returnData.getData()) {
                CollectionUtils.runOnObjectOrCollection(returnData.getData(), SensitiveUtils::hideObject);
            }
        }
        return body;
    }
}
